import { resolve } from 'path'
import { loadEnv } from 'vite'
import type { UserConfig, ConfigEnv } from 'vite'
import Vue from '@vitejs/plugin-vue'
import VueJsx from '@vitejs/plugin-vue-jsx'
import progress from 'vite-plugin-progress'
import EslintPlugin from 'vite-plugin-eslint'
import { ViteEjsPlugin } from 'vite-plugin-ejs'
// import PurgeIcons from 'vite-plugin-purge-icons'
import ServerUrlCopy from 'vite-plugin-url-copy'
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { createStyleImportPlugin, ElementPlusResolve } from 'vite-plugin-style-import'
import UnoCSS from 'unocss/vite'
import { visualizer } from 'rollup-plugin-visualizer'
import Icons from 'unplugin-icons/vite'
import { prismjsPlugin } from 'vite-plugin-prismjs'

// import IconsResolver from "unplugin-icons/resolver";
import inspect from 'vite-plugin-inspect'
import optimizeDeps from './optimizeDeps';

// https://vitejs.dev/config/
const root = process.cwd()

function pathResolve(dir: string) {
  return resolve(root, '.', dir)
}

export default ({ command, mode }: ConfigEnv): UserConfig => {
  let env = {} as any
  const port = env.VITE_APP_PORT || env.npm_config_port || 80 // 端口
  const isProd = env.NODE_ENV === 'production' // 是否生产环境

  const isBuild = command === 'build'
  if (!isBuild) {
    env = loadEnv(process.argv[3] === '--mode' ? process.argv[4] : process.argv[3], root)
  } else {
    env = loadEnv(mode, root)
  }

  return {
    base: env.VITE_APP_PUBLIC_PATH,
    plugins: [
      Vue({
        script: {
          // 开启defineModel
          defineModel: true
        }
      }),
      inspect(),
      VueJsx(),
      ServerUrlCopy(),
      progress(),
      env.VITE_USE_ALL_ELEMENT_PLUS_STYLE === 'false'
        ? createStyleImportPlugin({
            resolves: [ElementPlusResolve()],
            libs: [
              {
                libraryName: 'element-plus',
                esModule: true,
                resolveStyle: (name) => {
                  if (name === 'click-outside') {
                    return ''
                  }
                  return `element-plus/es/components/${name.replace(/^el-/, '')}/style/css`
                }
              }
            ]
          })
        : undefined,
      EslintPlugin({
        cache: true,
        failOnWarning: false,
        failOnError: false,
        include: ['src/**/*.vue', 'src/**/*.ts', 'src/**/*.tsx']
      }),
      VueI18nPlugin({
        runtimeOnly: true,
        compositionOnly: true,
        include: [resolve(__dirname, 'src/locales/**')]
      }),
      createSvgIconsPlugin({
        iconDirs: [
          pathResolve('src/assets/icons'),
          pathResolve('src/assets/codesvg'),
          pathResolve('src/assets/businesssvgs'),
          pathResolve('src/platform/wf/components/bpmnjs/bpmn-icons')
        ],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: true
      }),
      ViteEjsPlugin({
        title: env.VITE_APP_TITLE
      }),
      UnoCSS(),

      Icons({
        // 自动安装图标库
        autoInstall: true
      }),
      prismjsPlugin({
        languages: 'all',
        plugins: ['line-numbers', 'copy-to-clipboard'],
        theme: 'okaidia',
        css: true
      })
    ],

    css: {
      preprocessorOptions: {
        less: {
          additionalData: '@import "./src/styles/variables.module.less";',
          javascriptEnabled: true
        }
      }
    },
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx'],
      alias: [
        {
          find: 'vue-i18n',
          replacement: 'vue-i18n/dist/vue-i18n.cjs.js'
        },
        {
          find: /\@\//,
          replacement: `${pathResolve('src')}/`
        },
        {
          find: /\@base\//,
          replacement: `${pathResolve('src/platform/base')}/`
        },
        {
          find: /\@uni\//,
          replacement: `${pathResolve('src/platform/uni')}/`
        },
        {
          find: /\@code\//,
          replacement: `${pathResolve('src/platform/code')}/`
        },
        {
          find: /\@data\//,
          replacement: `${pathResolve('src/platform/data')}/`
        },
        {
          find: /\@wf\//,
          replacement: `${pathResolve('src/platform/wf')}/`
        },
        {
          find: /\@job\//,
          replacement: `${pathResolve('src/platform/job')}/`
        },
        {
          find: /\@monitor\//,
          replacement: `${pathResolve('src/platform/monitor')}/`
        },
        {
          find: /\@observer\//,
          replacement: `${pathResolve('src/platform/observer')}/`
        },
        {
          find: /\@report\//,
          replacement: `${pathResolve('src/platform/report')}/`
        },
        {
          find: /\@conn\//,
          replacement: `${pathResolve('src/platform/conn')}/`
        },
        {
          find: /\@samples\//,
          replacement: `${pathResolve('src/platform/samples')}/`
        },
        {
          find: /\@slc\//,
          replacement: `${pathResolve('src/platform/slc')}/`
        },
        {
          find: /\@platformComponents\//,
          replacement: `${pathResolve('src/platform/data/views/data/dataDevelopment/components')}/`
        }
      ]
    },
    esbuild: {
      pure: env.VITE_DROP_CONSOLE === 'true' ? ['console.log'] : undefined,
      drop: env.VITE_DROP_DEBUGGER === 'true' ? ['debugger'] : undefined
    },
    build: {
      target: 'es2015',
      // 生成文件的目录名称
      outDir: `dist/${env.VITE_APP_OUTPUT_DIR}/${env.VITE_APP_PUBLIC_PATH}`,
      sourcemap: env.VITE_SOURCEMAP === 'true',
      minify: 'terser',
      // brotliSize: false,
      rollupOptions: {
        plugins: env.VITE_USE_BUNDLE_ANALYZER === 'true' ? [visualizer()] : undefined,
        // 拆包
        output: {
          compact: true,
          minifyInternalExports: true,
          manualChunks: {
            'vue-chunks': ['vue', 'vue-router', 'pinia', 'vue-i18n', 'vue-draggable-plus', 'vue-echarts'],
            'element-plus': ['element-plus'],
            'wang-editor': ['@wangeditor/editor', '@wangeditor/editor-for-vue'],
            'monaco-editor': ['monaco-editor'],
            'echarts': ['echarts', 'echarts-wordcloud'],
            'bpmnjs': ['bpmn-js'],
            'bpmnjs-ext': ['bpmn-js-bpmnlint', 'bpmn-js-color-picker', 'bpmn-js-connectors-extension'
              , 'bpmn-js-external-label-modeling', 'bpmn-js-properties-panel', 'bpmn-js-token-simulation'],
            'bpmn': ['bpmn-moddle', 'bpmnlint'],
          }
        }
      },
      cssCodeSplit: !(env.VITE_USE_CSS_SPLIT === 'false'),
      cssTarget: ['chrome31']
    },
    server: {
      watch: {
        usePolling: false,
      },
      host: '0.0.0.0',
      port: Number(port),
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_APP_GATEWAY_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp('^' + env.VITE_APP_BASE_API), '')
        }
      },
      hmr: {
        overlay: false,
        protocol: 'ws',
      }
    },
    optimizeDeps: {
      include: optimizeDeps
    }
  }
}
